import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { scheduleService } from '@/services/scheduleService';
import type {
  ScheduleCreate,
  ScheduleUpdate,
  ScheduleResponse,
  ScheduleDetailResponse,
  ScheduleList,
  ScheduleStats,
  ScheduleFilters
} from '@/types/schedule';

export const useScheduleStore = defineStore('schedule', () => {
  const schedules = ref<ScheduleResponse[]>([]);
  const currentSchedule = ref<ScheduleDetailResponse | null>(null);
  const scheduleStats = ref<ScheduleStats | null>(null);
  const upcomingSchedules = ref<ScheduleResponse[]>([]);
  const isLoading = ref(false);
  const error = ref<string | null>(null);
  const totalSchedules = ref(0);

  const schedulesByDate = computed(() => {
    const grouped: Record<string, ScheduleResponse[]> = {};
    
    schedules.value.forEach(schedule => {
      const date = schedule.start_time.split('T')[0];
      if (!grouped[date]) {
        grouped[date] = [];
      }
      grouped[date].push(schedule);
    });

    Object.keys(grouped).forEach(date => {
      grouped[date].sort((a, b) => 
        new Date(a.start_time).getTime() - new Date(b.start_time).getTime()
      );
    });

    return grouped;
  });

  const pendingSchedules = computed(() => 
    schedules.value.filter(s => s.status === 'pending')
  );

  const highPrioritySchedules = computed(() => 
    schedules.value.filter(s => s.priority === 'high' || s.priority === 'urgent')
  );

  const todaySchedules = computed(() => {
    const today = new Date().toISOString().split('T')[0];
    return schedulesByDate.value[today] || [];
  });

  const clearError = () => {
    error.value = null;
  };

  const setLoading = (loading: boolean) => {
    isLoading.value = loading;
  };

  const fetchSchedules = async (filters: ScheduleFilters = {}) => {
    try {
      setLoading(true);
      clearError();
      
      const response: ScheduleList = await scheduleService.getSchedules(filters);
      schedules.value = response.schedules;
      totalSchedules.value = response.total;
      
      return response;
    } catch (err: unknown) {
      const errorResponse = err as { response?: { data?: { detail?: string } } };
      error.value = errorResponse.response?.data?.detail || '获取日程列表失败';
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const fetchUpcomingSchedules = async (daysAhead: number = 7, memberId?: number | null) => {
    try {
      setLoading(true);
      clearError();
      
      upcomingSchedules.value = await scheduleService.getUpcomingSchedules(daysAhead, memberId);
      return upcomingSchedules.value;
    } catch (err: unknown) {
      const errorResponse = err as { response?: { data?: { detail?: string } } };
      error.value = errorResponse.response?.data?.detail || '获取即将到来的日程失败';
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const fetchScheduleStats = async (startDate?: string | null, endDate?: string | null) => {
    try {
      setLoading(true);
      clearError();
      
      scheduleStats.value = await scheduleService.getScheduleStats(startDate, endDate);
      return scheduleStats.value;
    } catch (err: unknown) {
      const errorResponse = err as { response?: { data?: { detail?: string } } };
      error.value = errorResponse.response?.data?.detail || '获取日程统计失败';
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const fetchScheduleById = async (id: number) => {
    try {
      setLoading(true);
      clearError();
      
      currentSchedule.value = await scheduleService.getSchedule(id);
      return currentSchedule.value;
    } catch (err: unknown) {
      const errorResponse = err as { response?: { data?: { detail?: string } } };
      error.value = errorResponse.response?.data?.detail || '获取日程详情失败';
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const createSchedule = async (data: ScheduleCreate) => {
    try {
      setLoading(true);
      clearError();
      
      const newSchedule = await scheduleService.createSchedule(data);
      schedules.value.unshift(newSchedule);
      totalSchedules.value++;
      
      return newSchedule;
    } catch (err: unknown) {
      const errorResponse = err as { response?: { data?: { detail?: string } } };
      error.value = errorResponse.response?.data?.detail || '创建日程失败';
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const updateSchedule = async (id: number, data: ScheduleUpdate) => {
    try {
      setLoading(true);
      clearError();
      
      const updatedSchedule = await scheduleService.updateSchedule(id, data);
      
      const index = schedules.value.findIndex(s => s.id === id);
      if (index !== -1) {
        schedules.value[index] = updatedSchedule;
      }
      
      if (currentSchedule.value?.id === id) {
        currentSchedule.value = { ...currentSchedule.value, ...updatedSchedule } as ScheduleDetailResponse;
      }
      
      return updatedSchedule;
    } catch (err: unknown) {
      const errorResponse = err as { response?: { data?: { detail?: string } } };
      error.value = errorResponse.response?.data?.detail || '更新日程失败';
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const deleteSchedule = async (id: number) => {
    try {
      setLoading(true);
      clearError();
      
      await scheduleService.deleteSchedule(id);
      
      schedules.value = schedules.value.filter(s => s.id !== id);
      totalSchedules.value--;
      
      if (currentSchedule.value?.id === id) {
        currentSchedule.value = null;
      }
    } catch (err: unknown) {
      const errorResponse = err as { response?: { data?: { detail?: string } } };
      error.value = errorResponse.response?.data?.detail || '删除日程失败';
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const fetchScheduleParticipants = async (scheduleId: number) => {
    try {
      setLoading(true);
      clearError();
      
      const participants = await scheduleService.getScheduleParticipants(scheduleId);
      
      if (currentSchedule.value?.id === scheduleId) {
        currentSchedule.value.participants = participants;
      }
      
      return participants;
    } catch (err: unknown) {
      const errorResponse = err as { response?: { data?: { detail?: string } } };
      error.value = errorResponse.response?.data?.detail || '获取日程参与者失败';
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const confirmScheduleParticipation = async (scheduleId: number, participantId: number) => {
    try {
      setLoading(true);
      clearError();
      
      const participant = await scheduleService.confirmScheduleParticipation(scheduleId, participantId);
      
      if (currentSchedule.value?.id === scheduleId) {
        const index = currentSchedule.value.participants.findIndex(p => p.id === participantId);
        if (index !== -1) {
          currentSchedule.value.participants[index] = participant;
        }
      }
      
      return participant;
    } catch (err: unknown) {
      const errorResponse = err as { response?: { data?: { detail?: string } } };
      error.value = errorResponse.response?.data?.detail || '确认日程参与失败';
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const clearCurrentSchedule = () => {
    currentSchedule.value = null;
  };

  return {
    schedules,
    currentSchedule,
    scheduleStats,
    upcomingSchedules,
    isLoading,
    error,
    totalSchedules,
    schedulesByDate,
    pendingSchedules,
    highPrioritySchedules,
    todaySchedules,
    clearError,
    fetchSchedules,
    fetchUpcomingSchedules,
    fetchScheduleStats,
    fetchScheduleById,
    createSchedule,
    updateSchedule,
    deleteSchedule,
    fetchScheduleParticipants,
    confirmScheduleParticipation,
    clearCurrentSchedule
  };
});